let editor = document.getElementById("editor");
const selection = window.getSelection()
editor.addEventListener("beforeinput", function (e) {
    e.preventDefault();
    if (e.inputType == "insertText" && /[a-zA-Z]/.test(e.data)) {
        insertText(e)
    } else if (e.inputType == "deleteContentBackward") {
        deletText(e)
    }
})

function insertText(e) {
    let anchorOffset = selection.anchorOffset //光标起始选中位置
    const focusOffset = selection.focusOffset //光标末尾位置
    console.log('添加', anchorOffset, focusOffset);
    const selectStr = selection.toString()
    let left = ''
    if (anchorOffset > 0) {
        left = editor.innerHTML.slice(0, anchorOffset)
    }
    const right = editor.innerHTML.slice(anchorOffset)
    if (selectStr) {
        editor.innerHTML = editor.innerHTML.replace(selectStr, e.data)
    } else {
        editor.innerHTML = left + e.data + right
    }
    //设置光标位置
    if (anchorOffset > focusOffset) {
        anchorOffset = focusOffset
    }
    selection.collapse(editor.childNodes[0], anchorOffset + 1)
}

function deletText() {
    const anchorOffset = selection.anchorOffset - 1
    console.log('删除', anchorOffset);
    const selectStr = selection.toString()
    if (!selectStr) {
        //单个删除
        let left = ''
        if (anchorOffset > 0) {
            left = editor.innerHTML.slice(0, anchorOffset)
        }
        const right = editor.innerHTML.slice(anchorOffset + 1)
        editor.innerHTML = left + right
        setCursor(anchorOffset)
    } else {
        //删除选中
        selection.deleteFromDocument()
    }
}


function setCursor(anchorOffset) {
    anchorOffset > 0 && selection.collapse(editor.childNodes[0], anchorOffset)
}

// function getRange(node, selection) {
//     const range = window.document.createRange()
//     range.setStart(node, 2)
//     range.setEnd(node, 3)
//     selection.addRange(range)
// }

// document.addEventListener('selectionchange', (e) => {
//     console.log(e);
// })
